//
//  JSNetManager.m
//  Zhaijia(SJD)
//
//  Created by mac on 17/3/14.
//  Copyright © 2017年 刘超. All rights reserved.
//

#import "JSNetManager.h"
#import "AFNetworking.h"
#import "GTMBase64.h"
#import "JSAlertHelper.h"
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>

/*! 固定16位 */
#define gkey			@"basepro.basepro." //自行修改
#define gIv             @"basepro.basepro." //自行修改
static NSMutableArray *tasks;
@implementation JSNetManager
/*!
 *  获得全局唯一的网络请求实例单例方法
 *
 *  @return 网络请求类JSNetManager单例
 */
+ (JSNetManager *)sharedJSNetManager
{
    /*! 为单例对象创建的静态实例，置为nil，因为对象的唯一性，必须是static类型 */
    static id sharedJSNetManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedJSNetManager = [[super allocWithZone:NULL] init];
    });
    return sharedJSNetManager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [self sharedJSNetManager];
}

- (id)copy
{
    return self;
}

+ (id)copyWithZone:(struct _NSZone *)zone
{
    return [self sharedJSNetManager];
}
+ (AFHTTPSessionManager *)sharedAFManager
{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 10.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", nil];
        /*! https 参数配置 */
        /*!
         采用默认的defaultPolicy就可以了. AFN默认的securityPolicy就是它, 不必另写代码. AFSecurityPolicy类中会调用苹果security.framework的机制去自行验证本次请求服务端放回的证书是否是经过正规签名.
         */
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
        securityPolicy.allowInvalidCertificates = YES;
        securityPolicy.validatesDomainName = NO;
        manager.securityPolicy = securityPolicy;
        
        /*! 自定义的CA证书配置如下： */
        /*! 自定义security policy, 先前确保你的自定义CA证书已放入工程Bundle */
        /*!
         https://api.github.com网址的证书实际上是正规CADigiCert签发的, 这里把Charles的CA根证书导入系统并设为信任后, 把Charles设为该网址的SSL Proxy (相当于"中间人"), 这样通过代理访问服务器返回将是由Charles伪CA签发的证书.
         */
        //        NSSet <NSData *> *cerSet = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
        //        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerSet];
        //        policy.allowInvalidCertificates = YES;
        //        manager.securityPolicy = policy;
        
        /*! 如果服务端使用的是正规CA签发的证书, 那么以下几行就可去掉: */
        //        NSSet <NSData *> *cerSet = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]];
        //        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:cerSet];
        //        policy.allowInvalidCertificates = YES;
        //        manager.securityPolicy = policy;
    });
    
    return manager;
}
+ (JSURLSessionTask *)js_requestWithType:(JSHttpRequestType)type
                               urlString:(NSString *)urlString
                              parameters:(NSMutableDictionary *)parameters
                            successBlock:(JSResponseSuccess)successBlock
                            failureBlock:(JSResponseFail)failureBlock
                                
{
    // 设置公共参数
    
    
    if (urlString == nil)
    {
        return nil;
    }
    
    JS_WeakSelf(self)
    /*! 检查地址中是否有中文 */
    NSString *URLString = [NSURL URLWithString:urlString] ? urlString : [self strUTF8Encoding:urlString];
    
    NSString *requestType;
    switch (type) {
        case 0:
            requestType = @"Get";
            break;
        case 1:
            requestType = @"Post";
            break;
        case 2:
            requestType = @"Put";
            break;
        case 3:
            requestType = @"Delete";
            break;
    }
    
    NSLog(@"******************** 请求参数 ***************************");
    NSLog(@"请求头: %@\n请求方式: %@\n请求URL: %@\n请求param: %@\n\n",[self sharedAFManager].requestSerializer.HTTPRequestHeaders, requestType, URLString, parameters);
    NSLog(@"********************************************************");
    
    JSURLSessionTask *sessionTask = nil;
    if (type == JSHttpRequestTypeGet)
    {
        sessionTask = [[self sharedAFManager ] GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (successBlock) {
                successBlock(responseObject);
            }
            [[weakself tasks] removeObject:sessionTask];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (failureBlock)
            {
                failureBlock(error);
            }
            [[weakself tasks] removeObject:sessionTask];
        }];
        
        
    }
    else if (type == JSHttpRequestTypePost)
    {
      sessionTask = [[self sharedAFManager ] POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (successBlock) {
                successBlock(responseObject);
            }
            [[weakself tasks] removeObject:sessionTask];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            if (failureBlock)
            {
                failureBlock(error);
            }
            [[weakself tasks] removeObject:sessionTask];
        }];
        
    }
    
    if (sessionTask)
    {
        [[weakself tasks] addObject:sessionTask];
    }
    
    return sessionTask;
}
/*!
 *  上传图片(多图)
 *
 *  @param parameters   上传图片预留参数---视具体情况而定 可移除
 *  @param imageArray   上传的图片数组
 *  @param fileName     上传的图片数组fileName
 *  @param urlString    上传的url
 *  @param successBlock 上传成功的回调
 *  @param failureBlock 上传失败的回调
 *  @param progress     上传进度
 */
+ (JSURLSessionTask *)js_uploadImageWithUrlString:(NSString *)urlString
                                       parameters:(NSDictionary *)parameters
                                       imageArray:(NSArray *)imageArray
                                         fileName:(NSString *)fileName
                                     successBlock:(JSResponseSuccess)successBlock
                                      failurBlock:(JSResponseFail)failureBlock
                                   upLoadProgress:(JSUploadProgress)progress{
    
    if (urlString == nil)
    {
        return nil;
    }
    
    JS_WeakSelf(self)
    /*! 检查地址中是否有中文 */
    NSString *URLString = [NSURL URLWithString:urlString] ? urlString : [self strUTF8Encoding:urlString];
    
    NSLog(@"******************** 请求参数 ***************************");
    NSLog(@"请求头: %@\n请求方式: %@\n请求URL: %@\n请求param: %@\n\n",[self sharedAFManager].requestSerializer.HTTPRequestHeaders, @"POST",URLString, parameters);
    NSLog(@"******************************************************");
    
    
    JSURLSessionTask *sessionTask = nil;
    sessionTask = [[self sharedAFManager] POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        /*! 出于性能考虑,将上传图片进行压缩 */
        [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            /*! image的压缩方法 */
            UIImage *resizedImage;
            /*! 此处是使用原生系统相册 */
//            if([obj isKindOfClass:[ALAsset class]])
//            {
//                // 用ALAsset获取Asset URL  转化为image
//                ALAssetRepresentation *assetRep = [obj defaultRepresentation];
//                
//                CGImageRef imgRef = [assetRep fullResolutionImage];
//                resizedImage = [UIImage imageWithCGImage:imgRef
//                                                   scale:1.0
//                                             orientation:(UIImageOrientation)assetRep.orientation];
//                //                imageWithImage
//                NSLog(@"1111-----size : %@",NSStringFromCGSize(resizedImage.size));
//                
//                resizedImage = [weakself imageWithImage:resizedImage scaledToSize:resizedImage.size];
//                NSLog(@"2222-----size : %@",NSStringFromCGSize(resizedImage.size));
//            }
//            else
//            {
//                /*! 此处是使用其他第三方相册，可以自由定制压缩方法 */
//                resizedImage = obj;
//            }
            /*! 此处是使用其他第三方相册，可以自由定制压缩方法 */
            resizedImage = obj;
            /*! 此处压缩方法是jpeg格式是原图大小的0.8倍，要调整大小的话，就在这里调整就行了还是原图等比压缩 */
            NSData *imgData = UIImageJPEGRepresentation(resizedImage, 0.8);
            
            /*! 拼接data */
            if (imgData != nil)
            {   // 图片数据不为空才传递 fileName
                //                [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
                
                [formData appendPartWithFileData:imgData
                                            name:[NSString stringWithFormat:@"picflie%ld",(long)idx]
                                        fileName:fileName
                                        mimeType:@"image/jpeg"];
                
            }
            
        }];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"上传进度--%lld,总进度---%lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        
        if (progress)
        {
            progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传图片成功 = %@",responseObject);
        if (successBlock)
        {
            successBlock(responseObject);
        }
        
        [[weakself tasks] removeObject:sessionTask];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failureBlock)
        {
            failureBlock(error);
        }
        [[weakself tasks] removeObject:sessionTask];
    }];
    
    if (sessionTask)
    {
        [[weakself tasks] addObject:sessionTask];
    }
    
    return sessionTask;

    
}
/**
  *  当前项目数据请求封装
  *  @methond        方法名
  *  @isShowLoad     是否显示加载视图
  *  @isShowFinish   是否显示加载完成视图
  *  @parameters     参数
  *  @successBlock   请求成功回调
  *  @failureBlock   请求失败回调
  */
+(void)js_courrentProjectRequestWithMouth:(NSString *) methond
                                    cache:(BOOL)isCache
                        ifShowFinishStatu:(BOOL)isShowFinish
                               parameters:(NSMutableDictionary *)parameters
                             successBlock:(JSResponseSuccess)successBlock
                             failureBlock:(JSResponseFail)failureBlock{
    
    
   
    BOOL safe = NO;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"method"]   = methond;
    dict[@"version"]  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    dict[@"time"]     = [self getTime];
    dict[@"plat"]     = @"1";
    dict[@"sign"]     = [self getDeviceIdentifier];
    NSLog(@"请求参数(%@)==%@ data==%@,URL==%@",methond,parameters,parameters,BASE_URL);
    dict[@"data"] = [self dictionaryToJson:parameters];
    NSString *parametersStr = nil;
    if (safe) {
        parametersStr = [self AES128Encrypt:dict];
    }else{
        parametersStr = [self dictionaryToJson:dict];
    }
    [self js_requestWithType:JSHttpRequestTypePost urlString:BASE_URL parameters:@{@"params":parametersStr}.mutableCopy successBlock:^(id response) {
        [MBManager hideAlert];
        NSDictionary *responseDic = nil;
        //-----> 华丽的分割线  <-------
        if (safe) {
            NSString *str = response[@"ret"];
            NSLog(@"str-->%@", str);
            responseDic = [self AES128Decrypt:str];
        }else{
            responseDic = response;
        }
        //-----> 华丽的分割线  <-------
        if (successBlock) {
            successBlock(responseDic);
        }
        JSLog(@"【数据请求成功】%@",responseDic);
        
    } failureBlock:^(NSError *error) {
        [MBManager hideAlert];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
        //        });
        [JSAlertHelper showFailHideAfterDelay:2 text:JSLocalizedString(kLocalizableNetworkError) inView:nil animation:YES];
        JSLog(@"error-->%@", error);
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}
/*!
 *  上传图片(多图)
 *
 *  @param parameters   上传图片预留参数---视具体情况而定 可移除
 *  @param imageArray   上传的图片数组
 *  @param fileName     上传的图片数组fileName
 *  @param urlString    上传的url
 *  @param successBlock 上传成功的回调
 *  @param failureBlock 上传失败的回调
 *  @param progress     上传进度
 */
+ (JSURLSessionTask *)js_currentUploadImageWithUrlString:(NSString *)urlString
                                         showLoadingView:(UIView *)inView
                                              parameters:(NSDictionary *)parameters
                                              imageArray:(NSArray *)imageArray
                                                fileName:(NSString *)fileName
                                            successBlock:(JSResponseSuccess)successBlock
                                             failurBlock:(JSResponseFail)failureBlock
                                          upLoadProgress:(JSUploadProgress)progress{
    if (urlString == nil)
    {
        return nil;
    }
    BOOL safe = YES;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"method"]   = @"uploadImg";
    dict[@"version"]  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    dict[@"time"]     = [self getTime];
    dict[@"plat"]     = @"1";
    dict[@"sign"]     = [self getDeviceIdentifier];
    dict[@"data"] = [self dictionaryToJson:parameters];
    NSString *parametersStr = nil;
    if (safe) {
        parametersStr = [self AES128Encrypt:dict];
    }else{
        parametersStr = [self dictionaryToJson:dict];
    }
    JS_WeakSelf(self)
    /*! 检查地址中是否有中文 */
    NSString *URLString = [NSURL URLWithString:urlString] ? urlString : [self strUTF8Encoding:urlString];
    NSLog(@"******************** 请求参数 ***************************");
    NSLog(@"请求头: %@\n请求方式: %@\n请求URL: %@\n请求param: %@\n\n",[self sharedAFManager].requestSerializer.HTTPRequestHeaders, @"POST",URLString, dict);
    NSLog(@"******************************************************");
    JSURLSessionTask *sessionTask = nil;
    JSLog(@"请求参数 %@", parametersStr);
    sessionTask = [[self sharedAFManager] POST:URLString parameters:@{@"params":parametersStr}.mutableCopy constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /*! 出于性能考虑,将上传图片进行压缩 */
        [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *resizedImage = obj;
        NSData *imgData = UIImageJPEGRepresentation(resizedImage, 0.8);
            if (imgData != nil)
            {   // 图片数据不为空才传递 fileName
                //                [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
                
                [formData appendPartWithFileData:imgData
                                            name:[NSString stringWithFormat:@"picflie%ld",(long)idx]
                                        fileName:fileName
                                        mimeType:@"image/png"];
                
            }
        
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度--%lld,总进度---%lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        
        if (progress)
        {
            progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传图片成功 = %@",responseObject);
        NSDictionary *responseDic = nil;
        if (safe) {
            NSString *str = responseObject[@"ret"];
            NSLog(@"str-->%@", str);
            responseDic = [self AES128Decrypt:str];
        }else{
            responseDic = responseObject;
        }
        if (successBlock)
        {
            successBlock(responseDic);
        }
        
        [[weakself tasks] removeObject:sessionTask];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock)
        {
            failureBlock(error);
        }
        [[weakself tasks] removeObject:sessionTask];
    }];
    if (sessionTask)
    {
        [[weakself tasks] addObject:sessionTask];
    }
    return sessionTask;
}

+ (JSURLSessionTask *)js_currentUploadImageWithUrlString:(NSString *)urlString
                                         showLoadingView:(UIView *)inView
                                                  method:(NSString *)method
                                              parameters:(NSDictionary *)parameters
                                              imageArray:(NSArray *)imageArray
                                                fileName:(NSString *)fileName
                                            successBlock:(JSResponseSuccess)successBlock
                                             failurBlock:(JSResponseFail)failureBlock
                                          upLoadProgress:(JSUploadProgress)progress{
    if (urlString == nil || !method)
    {
        return nil;
    }
    BOOL safe = NO;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"method"]   = method;
    dict[@"version"]  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    dict[@"time"]     = [self getTime];
    dict[@"plat"]     = @"1";
    dict[@"sign"]     = [self getDeviceIdentifier];
    dict[@"data"] = [self dictionaryToJson:parameters];
    NSString *parametersStr = nil;
    if (safe) {
        parametersStr = [self AES128Encrypt:dict];
    }else{
        parametersStr = [self dictionaryToJson:dict];
    }
    JS_WeakSelf(self)
    /*! 检查地址中是否有中文 */
    NSString *URLString = [NSURL URLWithString:urlString] ? urlString : [self strUTF8Encoding:urlString];
    NSLog(@"******************** 请求参数 ***************************");
    NSLog(@"请求头: %@\n请求方式: %@\n请求URL: %@\n请求param: %@\n\n",[self sharedAFManager].requestSerializer.HTTPRequestHeaders, @"POST",URLString, dict);
    NSLog(@"******************************************************");
    JSURLSessionTask *sessionTask = nil;
    JSLog(@"请求参数 %@", parametersStr);
    sessionTask = [[self sharedAFManager] POST:URLString parameters:@{@"params":parametersStr}.mutableCopy constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /*! 出于性能考虑,将上传图片进行压缩 */
        [imageArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIImage *resizedImage = obj;
            NSData *imgData = UIImageJPEGRepresentation(resizedImage, 0.8);
            if (imgData != nil)
            {   // 图片数据不为空才传递 fileName
                //                [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
                NSString *type = [UIImage contentTypeForImageData:imgData];
                JSLog(@"当前图片类型 %@ \n", type);
                [formData appendPartWithFileData:imgData
                                            name:[NSString stringWithFormat:@"picflie%ld",(long)idx]
                                        fileName:[NSString stringWithFormat:@"%@.%@",fileName,type]
                                        mimeType:[NSString stringWithFormat:@"image/%@",type]];
                
            }
            
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度--%lld,总进度---%lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        
        if (progress)
        {
            progress(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传图片成功 = %@",responseObject);
        NSDictionary *responseDic = nil;
        if (safe) {
            NSString *str = responseObject[@"ret"];
            NSLog(@"str-->%@", str);
            responseDic = [self AES128Decrypt:str];
        }else{
            responseDic = responseObject;
        }
        if (successBlock)
        {
            successBlock(responseDic);
        }
        
        [[weakself tasks] removeObject:sessionTask];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock)
        {
            failureBlock(error);
        }
        [[weakself tasks] removeObject:sessionTask];
    }];
    if (sessionTask)
    {
        [[weakself tasks] addObject:sessionTask];
    }
    return sessionTask;
}

#pragma mark - url 中文格式化
+ (NSString *)strUTF8Encoding:(NSString *)str
{
    /*! ios9适配的话 打开第一个 */
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 9.0)
    {
        return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
    }
    else
    {
        return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
}
#pragma mark - 取消 Http 请求
/*!
 *  取消所有 Http 请求
 */
+ (void)js_cancelAllRequest
{
    // 锁操作
    @synchronized(self)
    {
        [[self tasks] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self tasks] removeAllObjects];
    }
}

/*!
 *  取消指定 URL 的 Http 请求
 */
+ (void)js_cancelRequestWithURL:(NSString *)URL
{
    if (!URL)
    {
        return;
    }
    @synchronized (self)
    {
        [[self tasks] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL])
            {
                [task cancel];
                [[self tasks] removeObject:task];
                *stop = YES;
            }
        }];
    }
}
+ (NSMutableArray *)tasks
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"创建数组请求任务");
        tasks = [[NSMutableArray alloc] init];
    });
    return tasks;
}
/*! 对图片尺寸进行压缩 */
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    if (newSize.height > 375/newSize.width*newSize.height)
    {
        newSize.height = 375/newSize.width*newSize.height;
    }
    
    if (newSize.width > 375)
    {
        newSize.width = 375;
    }
    
    UIImage *newImage = [UIImage needCenterImage:image size:newSize scale:1.0];
    
    return newImage;
}
@end
@implementation JSNetManager (tools)
+ (NSString *)getTime
{
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}


+ (NSString *)getDeviceIdentifier
{
    
    NSUUID * currentDeviceUUID  = [UIDevice currentDevice].identifierForVendor;
    NSString * currentDeviceUUIDStr = currentDeviceUUID.UUIDString;
    currentDeviceUUIDStr = [currentDeviceUUIDStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    currentDeviceUUIDStr = [currentDeviceUUIDStr lowercaseString];
    
    return currentDeviceUUIDStr;
}

//接口MD5加密
+ (NSString *)getPsdMD5String:(NSString *)psd{
    
    NSString *string = [NSString stringWithFormat:@"%@",psd];
    NSLog(@"sign = %@",string);
    const char *cStr = [string UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    NSString *myCode = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                        result[0], result[1], result[2], result[3],
                        result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11],
                        result[12], result[13], result[14], result[15]];
    
    return myCode;
    
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
    
    NSError *parseError = nil;
    if (!dic) {
        dic = @{};
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


+ (NSArray *)arrayWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                      
                                                     options:NSJSONReadingMutableContainers
                      
                                                       error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return array;
    
}

+(NSString *)jsonStringWithArray:(NSArray *)array {
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
+(NSString *)AES128Encrypt:(NSDictionary *)dic
{
    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSString *jsonStr    = [self dictionaryToJson:dic];
    NSData* data         = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSInteger dataLength = [data length];
    
    NSInteger diff       = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    NSInteger newSize    = 0;
    
    if(diff > 0)
    {
        newSize = dataLength + diff;
    }
    
    char dataPtr[newSize];
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i++)
    {
        dataPtr[i + dataLength] = 0x00;
    }
    
    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer      = malloc(bufferSize);
    memset(buffer, 0, bufferSize);
    
    size_t numBytesCrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,               //No padding
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          ivPtr,
                                          dataPtr,
                                          sizeof(dataPtr),
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        
        return [GTMBase64 stringByEncodingData:resultData];
    }
    free(buffer);
    return nil;
}

+(NSDictionary *)AES128Decrypt:(NSString *)encryptText
{
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [gkey getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [gIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSData *data          = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger dataLength = [data length];
    size_t bufferSize     = dataLength + kCCBlockSizeAES128;
    void *buffer          = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        
        NSData *resultData    = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        NSString * jsonResult = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        jsonResult            = [jsonResult stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
        NSDictionary * dic    = [self dictionaryWithJsonString:jsonResult];
        
        return dic;
    }
    free(buffer);
    return nil;
}


@end
